package gov.gfbzb.advice.controller;

import gov.gfbzb.advice.annotation.AuthCheck;
import gov.gfbzb.advice.controller.dto.ChangePassWordDTO;
import gov.gfbzb.advice.controller.dto.LoginDTO;
import gov.gfbzb.advice.controller.dto.UserDTO;
import gov.gfbzb.advice.controller.vo.AdviceVO;
import gov.gfbzb.advice.controller.vo.UserVO;
import gov.gfbzb.advice.entity.Advice;
import gov.gfbzb.advice.exception.BusinessException;
import gov.gfbzb.advice.exception.ErrorCode;
import gov.gfbzb.advice.util.StringUtil;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import gov.gfbzb.advice.util.Result;
import gov.gfbzb.advice.service.IUserService;
import gov.gfbzb.advice.entity.User;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserController 前端控制器
 * @author 小宇
 * @since 2025-07-05
 */
@RestController
@Tag(name = "用户控制器")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
    *  用户注册
    */
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result register(@RequestBody UserDTO userDTO) {
        // 非空判断
        if (StringUtils.isAnyBlank(userDTO.getUserName(), userDTO.getPassword(), userDTO.getPhone())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userService.register(userDTO)){
            return Result.success("通过");
        }
        return Result.error("失败");
    }

    /**
     *  用户编辑
     */
    @AuthCheck(mustAdmin = "admin")
    @PostMapping("/edit")
    @Operation(summary = "用户编辑")
    public Result edit(@RequestBody UserDTO userDTO) {
        User user = userService.getById(userDTO.getId());
        BeanUtils.copyProperties(userDTO, user,"password","is_delete","user_status","create_time","update_time");
        if (userService.updateById(user)){
            return Result.success("通过");
        }
        return Result.error("失败");
    }

    /**
     *  修改密码
     */
    @PostMapping("/editPassWord")
    @Operation(summary = "修改密码")
    public Result editPassWord(@RequestBody ChangePassWordDTO changePassWordDTO) {
        if (StringUtils.isAnyBlank(changePassWordDTO.getPhone(), changePassWordDTO.getOldPassWord(), changePassWordDTO.getNewPassWord())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", changePassWordDTO.getPhone());
        queryWrapper.eq("password", StringUtil.md5(changePassWordDTO.getOldPassWord()));
        // 查询用户
        User theUser = userService.getOne(queryWrapper);
        if (theUser == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (changePassWordDTO.getOldPassWord().equals(changePassWordDTO.getNewPassWord())){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"新旧密码相同");
        }
        // 获取调用接口人的信息
        Claims claims = userService.getClaims();
        String loginUserPhone = claims.get("phone", String.class);
        if (!loginUserPhone.equals(theUser.getPhone())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"请勿修改别人密码");
        }
        theUser.setPassword(StringUtil.md5(changePassWordDTO.getNewPassWord()));
        if (userService.updateById(theUser)){
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    /**
     * 重置密码
     */
    @AuthCheck(mustAdmin = "admin")
    @GetMapping("/resetPassWord")
    @Operation(summary = "重置密码")
    public Result resetPassWord(@RequestParam(name = "id") Integer id) {
        User theUser = userService.getById(id);
        theUser.setPassword(StringUtil.md5("123456"));
        if (userService.updateById(theUser)){
            return Result.success("重置成功");
        }
        return Result.error("重置失败");
    }

    /**
     * 禁用用户
     * @param id 用户id
     * @return  result
     */
    @AuthCheck(mustAdmin = "admin")
    @PostMapping("/ban")
    @Operation(summary = "禁用用户")
    public Result ban(@RequestParam(name = "id")Integer id){
        User theUser = userService.getById(id);
        if (theUser == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (theUser.getUserStatus() == 1){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户已禁用");
        }
        theUser.setUserStatus(1);
        if (userService.updateById(theUser)){
            return Result.success("禁用成功");
        }
        return Result.error("禁用失败");
    }

    /**
     * 解禁用户
     * @param id 用户id
     * @return  result
     */
    @AuthCheck(mustAdmin = "admin")
    @PostMapping("/open")
    @Operation(summary = "解禁用户")
    public Result open(@RequestParam(name = "id")Integer id){
        User theUser = userService.getById(id);
        if (theUser == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (theUser.getUserStatus() == 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户已启用");
        }
        theUser.setUserStatus(0);
        if (userService.updateById(theUser)){
            return Result.success("启用成功");
        }
        return Result.error("启用失败");
    }

    /**
    *  用户登录
    */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result login(@RequestBody LoginDTO loginDTO) {
        // 非空判断
        if (StringUtils.isAnyBlank(loginDTO.getPhone(), loginDTO.getPassword(), loginDTO.getTimestamp(), loginDTO.getCode())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return Result.success(userService.login(loginDTO));
    }

    /**
     *  删除
     */
    @GetMapping("/delete")
    @AuthCheck(mustAdmin = "admin")
    @Operation(summary = "通过id删除")
    public Result delete(@RequestParam(name = "id") Integer id) {
        User user =userService.getById(id);
        user.setIsDelete(1);
        return Result.success(userService.saveOrUpdate(user));
    }

    /**
     * 通过时间戳获取登录验证码
     * 120秒过期
     */
    @Operation(summary = "通过时间戳获取登录验证码")
    @GetMapping("/getCheckData")
    public Result getCheckData(@RequestParam(name = "timestamp") String timestamp) {
        String checkData = userService.getCheckData(timestamp);
        // 返回
        return Result.success(checkData);
    }

    /**
    *  根据id查询
    */
    @AuthCheck(mustAdmin = "admin")
    @GetMapping("/getById")
    @Operation(summary = "根据id查询")
    public Result findOne(@RequestParam(name = "id") Integer id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return Result.success(userService.getOne(queryWrapper));
    }

    /**
    *  分页查询
    */
    @AuthCheck(mustAdmin = "admin")
    @GetMapping("/page")
    @Operation(summary = "分页查询")
    public Result findPage(@RequestParam(name = "pageNum") Integer pageNum,
                           @RequestParam(name = "pageSize") Integer pageSize,
                           @RequestParam(name = "role",required = false) String role,
                           @RequestParam(name = "county",required = false) String county) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(role)){
            queryWrapper.eq("role", role);
        }
        if (StringUtils.isNotBlank(county)){
            queryWrapper.like("county", county);
        }
        queryWrapper.orderByDesc("id");

        // 获取分页数据
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);

        // 转化为 VO
        List<UserVO> userVOList = page.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).toList();

        // 构建分页响应对象
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("records", userVOList);        // 数据列表
        resultData.put("total", page.getTotal());       // 总记录数
        resultData.put("pages", page.getPages());       // 总页数
        resultData.put("current", page.getCurrent());   // 当前页码
        resultData.put("size", page.getSize());         // 每页大小
        return Result.success(resultData);
    }
}

